<script lang="ts" setup>
import PageCaontainer from '@/arco-components/PageContainer';
import { ref, onMounted, reactive } from 'vue';
import shrinkLeft from '@/assets/images/shrinkLeft.svg';
import activeShrinkLeft from '@/assets/images/activeShrinLeft.svg';
import API from '@/services';
import AQueryHeader, { useQueryHeader } from '@dangojs/a-query-header';
import AQueryTable from '@dangojs/a-query-table';
import { Message, Modal } from '@arco-design/web-vue';
import createScenes from './createScenes/index.vue';
import { store } from '@/store';
import Tree from '@/components/Tree/index.vue';

const toggle = ref(false);
const shrinkIcon = ref(shrinkLeft);
// 获取api
const {
  scene: {
    getSceneGroupRoot, // 场景树
    putSceneGroup, // 左侧修改场景分组
    postSceneGroup, // 左侧添加场景分组
    deleteSceneGroupById, // 左侧删除场景分组

    postSceneList, // 右侧场景列表
    deleteSceneDeleteById, // 右侧删除场景
    putSceneStatusById // 右侧改变场景状态
  }
} = API;
const scenesForm = reactive({
  cnName: '',
  status: '',
  groupId: '', // 当前分组id
  id: '' // 场景id
});
const statusOptions = [
  {
    label: '正常',
    value: 0
  },
  {
    label: '禁用',
    value: 1
  },
  {
    label: '草稿', // 还有一个草稿2,状态为3
    value: 2
  }
];
const querytableRef = ref<any>(null);
const columns: any[] = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 60
  },
  {
    title: '场景名称',
    dataIndex: 'cnName',
    width: 160
  },
  {
    title: '场景描述',
    dataIndex: 'description',
    width: 160
  },
  {
    title: '状态',
    width: 160,
    slotRenderName: 'scenesStatus'
  },
  {
    title: '操作',
    width: 180,
    fixed: 'right',
    slotRenderName: 'operate'
  }
];
const createScenesRef = ref();
const loading = ref(false);
const treeRef = ref();

// 折叠展开
const changeFold = () => {
  toggle.value = !toggle.value;
};

// 请求列表数据
const fetchList = (id: any) => {
  scenesForm.groupId = id;
};

const { onAutoSubmit, params } = useQueryHeader(scenesForm, true);
// 获取列表
const requestData = async (query: any) => {
  loading.value = true;
  try {
    const { code, data }: any = await postSceneList(query);
    if (code === 200 && Array.isArray(data?.list)) {
      loading.value = false;
      return {
        success: true,
        data: data.list,
        total: Number(data.total)
      };
    }
    return {
      success: true,
      data: [],
      total: 0
    };
  } catch (e) {
    loading.value = false;
  }
};

// 点击编辑
const onEdit = (id: number) => {
  store.commit('scenesManage/changeCurrentStep', 1);
  store.commit('scenesManage/resetFormStep1');
  store.commit('scenesManage/resetFormStep2');
  store.commit('scenesManage/resetFormStep3');
  createScenesRef.value.showDrawer(id);
};

// 改变场景状态(0-正常，1-禁用，2-草稿1，3-草稿2)
const fetchScenesStatus = async (params: any) => {
  try {
    const res = await putSceneStatusById({ ...params });
    return res;
  } catch (error) {
    throw error;
  }
};

// 点击禁用
const onDisabled = (record: defs.SceneVO) => {
  let params = {
    id: record.id,
    status: 1
  };
  fetchScenesStatus(params)
    .then((res: any) => {
      if (res.code === 200) {
        Message.success('修改成功');
        querytableRef.value.reload();
      } else {
        Message.error(res.msg);
      }
    })
    .catch(() => {});
};

// 点击使用
const onUse = (record: defs.SceneVO) => {
  let params = {
    id: record.id,
    status: 0
  };
  fetchScenesStatus(params)
    .then((res: any) => {
      if (res.code === 200) {
        Message.success('修改成功');
        querytableRef.value.reload();
      } else {
        Message.error(res.msg);
      }
    })
    .catch(() => {});
};

// 点击删除
const fetchDelete = async (id: number) => {
  try {
    const res = await deleteSceneDeleteById({ id });
    return res;
  } catch (error) {
    throw error;
  }
};
const onDelete = (record: defs.SceneVO) => {
  Modal.confirm({
    modalClass: 'model-message-confirm',
    title: '是否确定删除该场景？',
    content: '删除后不可恢复',
    simple: false,
    closable: true,
    okText: '确认删除',
    okButtonProps: {
      style: {
        backgroundColor: '#FF1A3B'
      }
    },
    onBeforeOk: (done) => {
      fetchDelete(Number(record.id))
        .then((res: any) => {
          if (res.code === 200) {
            Message.success('删除成功');
            querytableRef.value.reload();
            treeRef.value.getTreeNodeList();
          } else {
            Message.error(res.msg);
          }
        })
        .finally(() => {
          done(true);
        });
    }
  });
};

// 点击创建场景
const onCreate = () => {
  createScenesRef.value.showDrawer();
};

// 更新表格(还要更新左侧的树)
const updateTable = () => {
  querytableRef.value.reload();
  treeRef.value.getTreeNodeList();
};

// 重置筛选条件
const onReset = () => {
  console.log('重置');
  scenesForm.cnName = '';
  scenesForm.status = '';
  scenesForm.groupId = '';
  scenesForm.id = '';
  treeRef.value.handleAll();
};
</script>
<template>
  <PageCaontainer>
    <template #extra>
      <a-button type="primary" @click="onCreate()"
        >+创建场景</a-button
      ></template
    >
    <div class="scenes_container">
      <div
        class="scenes_container-left"
        :class="
          toggle ? 'scenes_container-left-hidden' : 'scenes_container-left-show'
        "
      >
        <img
          :class="toggle ? 'shrink-right' : ''"
          @click="changeFold"
          :src="shrinkIcon"
          @mouseenter="
            () => {
              shrinkIcon = activeShrinkLeft;
            }
          "
          @mouseout="
            () => {
              shrinkIcon = shrinkLeft;
            }
          "
        />
        <Tree
          titles="场景分类管理"
          :listFn="getSceneGroupRoot"
          :delFn="deleteSceneGroupById"
          :reNameFn="putSceneGroup"
          :addFn="postSceneGroup"
          :isDrop="false"
          :isFuzzySearch="false"
          :isModifyParent="false"
          :isReNameFnOne="false"
          :isShowNum="true"
          suffixName="分类"
          :isFromScenes="true"
          @fetch-list="fetchList"
          ref="treeRef"
          :rootId="1"
        ></Tree>
      </div>
      <div class="scenes_container-right">
        <AQueryHeader
          @reset="onReset"
          @autoSubmit="onAutoSubmit"
          hideSubmitBtn
          :num="3"
          style="
            padding: 10px 16px 11px;
            box-sizing: border-box;
            border-bottom: 1px solid #e8ebf2;
          "
        >
          <AFormItem show-colon label="场景名称">
            <AInput
              v-model="scenesForm.cnName"
              placeholder="请输入"
              style="min-width: 190px"
              allow-clear
            />
          </AFormItem>
          <AFormItem show-colon label="状态">
            <ASelect
              v-model="scenesForm.status"
              :options="statusOptions"
              placeholder="请选择"
              style="min-width: 190px"
              allow-clear
            />
          </AFormItem>
        </AQueryHeader>
        <AQueryTable
          ref="querytableRef"
          :columns="columns"
          :request="requestData"
          :params="params"
          class="m-18 scense_table"
          v-loading="loading"
          :bordered="false"
        >
          <template #scenesStatus="{ record }">
            <span
              class="scense_table-status"
              :data-status="record.status"
            ></span>
            <span class="scense_table-desc">{{ record.statusType }}</span>
          </template>
          <template #operate="{ record }">
            <a-button type="text" @click="() => onEdit(record.id)"
              >编辑</a-button
            >
            <a-divider direction="vertical" />
            <a-button
              type="text"
              @click="() => onDisabled(record)"
              v-show="record.status === 0"
              >禁用</a-button
            >
            <!-- status === 3 使用为可点击状态, 2置灰 -->
            <a-button
              type="text"
              @click="() => onUse(record)"
              v-show="record.status !== 0"
              :disabled="record.status === 2"
              :style="
                record.status !== 2
                  ? {
                      color: '#396EFE'
                    }
                  : {
                      color: '#BBBFCC'
                    }
              "
              >使用</a-button
            >
            <a-divider direction="vertical" />
            <a-button type="text" @click="() => onDelete(record)"
              >删除</a-button
            >
          </template>
        </AQueryTable>
      </div>
    </div>
    <create-scenes ref="createScenesRef" @update="updateTable"></create-scenes>
  </PageCaontainer>
</template>

<style lang="scss" scoped>
.scenes_container {
  background-color: #fff;
  display: flex;
  height: 100%;
  &-left {
    border-right: 1px solid #e8ebf2;
    transition: width 0.2s;
    position: relative;
    img {
      position: absolute;
      right: -12px;
      top: 48px;
      z-index: 100;
      width: 24px;
      height: 24px;
      background: #f6f8fc;
      padding: 7px;
      box-sizing: border-box;
      border-radius: 50%;
      cursor: pointer;
      box-shadow: 0px 0px 17px #eeeeee;
    }
    .shrink-right {
      transform: rotate(180deg);
    }
    .group-container {
      height: 100%;
      .tree-container {
        height: calc(100% - 90px);
        overflow-y: scroll;
      }
    }
  }
  &-left-show {
    width: 210px;
  }
  &-left-hidden {
    width: 0;
  }

  &-right {
    overflow: auto;
    flex: 1;
    display: flex;
    justify-content: flex-start;
    flex-direction: column;
    .scense_table-status {
      display: inline-block;
      width: 8px;
      height: 8px;
      border-radius: 4px;
      margin-right: 8px;
      &[data-status='0'] {
        background-color: #24d17e;
      }
      &[data-status='1'] {
        background-color: #ff1a3b;
      }
      &[data-status='2'],
      &[data-status='3'] {
        background-color: #396efe;
      }
      &-desc {
        font-size: 14px;
        color: #33353b;
        letter-spacing: 0;
        line-height: 22px;
        font-weight: 400;
      }
    }
  }
}
</style>
<style lang="scss">
.scenes_container-left-hidden {
  width: 0;
  .group-container {
    display: none;
  }
}
</style>
